/**
 * Created by bai on 2016/12/31.
 */


/**
 * TODO  地图基础功能：地图加载、底图切换、缩放、定位、图例、绘制图层
 */

var typhoonMap = {
    browser: {},
    map: {},
    currentBaseLayer: 'image',
    baseLayers: {
        image: L.layerGroup([L.tileLayer.chinaProvider('GaoDe.Satellite.Map', {
            maxZoom: 18,
            minZoom: 4
        }), L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion', {
            maxZoom: 18,
            minZoom: 4
        })]),
        dixing: L.layerGroup([L.tileLayer.chinaProvider('Google.Normal.Map', {
            maxZoom: 18,
            minZoom: 4
        })]),
        normal: L.layerGroup([L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
            maxZoom: 18,
            minZoom: 4
        })])
    },
    t_layers: {
        // "t_$typhoon_code":{"t_layer_group":{},"t_center_marker_layer":{},"t_path_layer":{},"t_path_point_layer":{},"t_f_path_layer":{},"t_f_path_point_layer":{}}
    },
    t_c_layer:{},
    t_c_shp_layer:{},
    // tileLayer:null,
    defZoom: 4,
    defCenter: [28.9, 128.9],
    drawn: {
        drawnItems: new L.FeatureGroup(),
        currentDrawLayer: null,
        polygon_options: {
            showArea: false,
            shapeOptions: {
                stroke: true,
                color: '#f00',
                weight: 2,
                dashArray: '5,10',
                opacity: 0.5,
                fill: true,
                fillColor: '#ff0',
                fillOpacity: 0.3,
                clickable: true
            }
        },
        onceEventListener: function (map, callback) {
            var that = this;
            // draw:created once event
            map.once('draw:created', function (e) {
                var type = e.layerType;
                that.currentDrawLayer = e.layer;
                that.drawnItems.addLayer(that.currentDrawLayer);
                // get layer data by layer type
                if (callback != null && callback != undefined) callback(e);
            });
        },
        clearDrawLayer: function (callback) {
            if (this.drawnItems) {
                this.drawnItems.clearLayers();
                //TODO do something else
                if (callback != null && callback != undefined) callback();
            }
        },
        drawPolygon: function (map, options, callback) {
            this.clearDrawLayer();
            this.onceEventListener(map, callback);
            var polygonDrawer = new L.Draw.Polygon(map, options || this.polygon_options);
            polygonDrawer.enable();
        },
        drawCircle: function (map, options, callback) {
            this.clearDrawLayer();
            this.onceEventListener(map, callback);
            var circleDrawer = new L.Draw.Circle(map, options || this.polygon_options);
            circleDrawer.enable();
        },
        drawRectangle: function (map, options, callback) {
            this.clearDrawLayer();
            this.onceEventListener(map, callback);
            var rectangleDrawer = new L.Draw.Rectangle(map, options || this.polygon_options);
            rectangleDrawer.enable();
        }
    },
    init: function (mapDiv, m) {
        this.tileLayer = this.baseLayers.image;
        this.map = L.map(mapDiv, {
            center: this.defCenter,
            zoom: this.defZoom,
            minZoom: 4,
            maxZoom: 18,
            maxBounds: [[-87.7, -98], [85, 283]],
            attributionControl: false,
            layers: [this.baseLayers.image],
            zoomControl: false
        });
        this.map._attr_ = 'bjs';
        this.guardLine();
        this.latlngControl();
        this.mapSourceControl();

        // draw layer group
        this.drawn.drawnItems.addTo(this.map);

        // eg: 切换底图
        // this.changeTilelayer('normal');
        // this.changeTilelayer('dixing');

        //this.drawCircle();
        this.t_c_layer = L.layerGroup();
        this.t_c_layer.addTo(this.map);
        this.t_c_shp_layer = L.layerGroup();
        this.t_c_shp_layer.addTo(this.map);

        //绘制shp
        //this.draw70Shp();
        // this.draw50Shp();
        // this.drawBizhiShp();
    },
    /**
     * 切换底图
     * @param tileLayerName
     */
    changeTilelayer: function (tileLayerName) {
        var _map = this.map;
        var _baseLayers = this.baseLayers;
        var _currentBaseLayer = this.currentBaseLayer;
        if (tileLayerName != _currentBaseLayer) {
            $.each(_baseLayers, function (i, val) {
                if (tileLayerName != i) {
                    _map.removeLayer(val);
                } else {
                    _baseLayers[tileLayerName].addTo(_map);
                    _currentBaseLayer = i;
                }
            });
            this.currentBaseLayer = _currentBaseLayer;
        }
    },
    /*drawCircle: function () {
        L.circle([25.627117, 119.73485], 500000, typhoonConstants.typhoonCircle_colors[1]).addTo(this.t_c_layer);
    },*/
    drawCircle: function () {
        L.circle([25.69583, 119.775], 500000, typhoonConstants.typhoonCircle_colors[0]).addTo(this.t_c_layer);
        L.circle([25.39722, 119.48611], 500000, typhoonConstants.typhoonCircle_colors[2]).addTo(this.t_c_layer);
    },
    drawMarker:function(){
        L.marker([25.69583, 119.775]).addTo(this.t_c_layer)
            .bindPopup('大练岛风电站')
            .closePopup();
        L.marker([25.39722, 119.48611]).addTo(this.t_c_layer)
            .bindPopup('兴化湾风电站')
            .closePopup();
    },
    clearCircle:function () {
        this.t_c_layer.clearLayers();
    },
    draw50Shp:function () {
        typhoonMap.drawShp("50",375);
        typhoonMap.drawShp("50",425);
        typhoonMap.drawShp("50",460);
        typhoonMap.drawShp("50",500);
        typhoonMap.drawShp("50",530);
        typhoonMap.drawShp("50",600);
    },
    draw70Shp:function () {
        typhoonMap.drawShp("70",5);
        typhoonMap.drawShp("70",6);
        typhoonMap.drawShp("70",7);
        typhoonMap.drawShp("70",8);
        typhoonMap.drawShp("70",9);
        typhoonMap.drawShp("70",10);
    },
    drawBizhiShp:function () {
        typhoonMap.drawShp("bizhi",5);
        typhoonMap.drawShp("bizhi",6);
        typhoonMap.drawShp("bizhi",7);
        typhoonMap.drawShp("bizhi",8);
        typhoonMap.drawShp("bizhi",9);
        typhoonMap.drawShp("bizhi",10);
        typhoonMap.drawShp("bizhi",20);
    },
    drawShp:function (type,name) {
        var that = this;
        var shpfile = new L.Shapefile('/statics/shp_data/'+type+"/"+name+'.zip', {
            style: function(feature) {
                return {
                    opacity: 0,
                    fillOpacity: 0.7,
                    radius: 0,
                    color: that.parseShpColor(type,name)
                }
            }
        });
        shpfile.addTo(this.t_c_shp_layer);
    },
    clearShp:function () {
        this.t_c_shp_layer.clearLayers();
    },
    parseShpColor:function (type,val) {
        if(type=="50"){
            if(val==375){
                return "#4575b5";
            }else if(val==425){
                return "#8da5ba";
            }else if(val==460){
                return "#d9e0bf";
            }else if(val==500){
                return "#fcdd9a";
            }else if(val==530){
                return "#f08159";
            }else if(val==600){
                return "#d62f27";
            }
        }else if(type=="70"){
            if(val==5){
                return "#ffff80";
            }else if(val==6){
                return "#fcdd5d";
            }else if(val==7){
                return "#f7ba3e";
            }else if(val==8){
                return "#d68522";
            }else if(val==9){
                return "#9e4410";
            }else if(val==10){
                return "#6b0601";
            }
        }else if(type=="bizhi"){
            if(val==5){
                return "#38a800";
            }else if(val==6){
                return "#6fc400";
            }else if(val==7){
                return "#b0e000";
            }else if(val==8){
                return "#ffff00";
            }else if(val==9){
                return "#ffaa00";
            }else if(val==10){
                return "#ff5500";
            }else if(val==20){
                return "#ff0000";
            }
        }

    },
    /**
     * 警戒线
     */
    guardLine: function () {
        var guardLine_24 = typhoonConstants.guardLine_24;// [[34.005024, 126.993568], [21.971252, 126.993568], [17.965860, 118.995521], [10.971050, 118.995521], [4.486270, 113.018959], [-0.035506, 104.998939]];
        // var guardLine_48 = typhoonConstants.guardLine_48;// [[-0.035506, 104.998939], [-0.035506, 119.962318], [14.968860, 131.981361], [33.959474, 131.981361]];
        this.t_guardLine =  L.polyline(guardLine_24, {color: '#FF0', weight: 1, opacity: 1, id: 'gl_24'});
        this.t_guardLine.addTo(this.map);//#F8E406
        // L.polyline(guardLine_48, {color: '#FF0', weight: 1, opacity: 1, dashArray: '5 5', id: 'gl_48'}).addTo(this.map);
        L.circleMarker([30.005024, 126.993568], {
            color: "#FFF",
            weight: 1,
            opacity: 0,
            fill: false
        }).setRadius(1).bindLabel("24<br/>小<br/>时<br/>警<br/>戒<br/>线", {
            noHide: true,
            className: "leaflet-label12"
        }).addTo(this.map);
        // L.circleMarker([27.959474, 131.981361], {
        //     color: "#FFF",
        //     weight: 1,
        //     opacity: 0,
        //     fill: false
        // }).setRadius(5).bindLabel("48<br/>小<br/>时<br/>警<br/>戒<br/>线", {
        //     noHide: true,
        //     className: "leaflet-label48"
        // }).addTo(this.map);
    },

    latlngControl: function () {
        var LatlngControl = L.Control.extend({
            initialize: function (foo, options) {
                L.Util.setOptions(this, options);
            },
            onAdd: function (map) {
                var loc = L.DomUtil.create('div', 'leaflet-control-location');
                loc.style.fontFamily = "Consolas,Arial";
                loc.style.clear = "none";
                loc.style.color = "#5195db";
                loc.innerHTML = "经度: 138.952   纬度: 28.913";
                return loc;
            }
        });
        this.map.addControl(new LatlngControl("latlngLocation", {position: 'bottomright'}));
        this.map.on("mousemove", function (e) {
            $(".leaflet-control-location").html("经度: " + Number(e.latlng.lng).toFixed(3) + "   纬度: " + Number(e.latlng.lat).toFixed(3));
        });
    },


    mapSourceControl: function () {
        var MapSourceControl = L.Control.extend({
            initialize: function (foo, options) {
                L.Util.setOptions(this, options);
            },
            onAdd: function (map) {
                var loc = L.DomUtil.create('div', 'leaflet-control-mapsource');
                loc.style.fontFamily = "Consolas,Arial";
                loc.style.clear = "none";
                loc.style.color = "#5195db";
                loc.innerHTML = "地图数据 &copy;AutoNavi";

                return loc;
            }
        });
        this.map.addControl(new MapSourceControl("mapSource", {position: 'bottomright'}));
    },


    showTyphoon: function (typhoonData, isPlay) {
        var that = this;
        $.getJSON('/statics/data/data.json', function (data) {
                that.drawTyphoon(data["typhoon"]);
            }
        );

    },
    showTyphoonByTfbh: function (tfbh) {
        var that = this;
        $.ajax({
            url: '/tfData/tf_path_data/' + tfbh + '.ajax',
            type: 'get',
            dataType: 'json',
            success: function (data) {
                // console.info(data);
                that.drawTyphoon_(data);
            }
        });
    },
    drawTyphoon_: function (tfDataMap) {
        var that = this;
        var tfbh = tfDataMap.tfbh;
        var name = tfDataMap.name;
        var dataArr = tfDataMap.pathData;
        //初始化台风图层对象
        this.resetTyphoonLayers(tfbh);
        var pathLen = dataArr.length;

        for (var idx = 0; idx < pathLen; idx++) {
            var data = dataArr[idx];
            var lat = Number(data.lat);
            var lng = Number(data.lon);

            var wcData = {
                'lat': lat,
                'lng': lng,
                'wc': that.getWindCircleData(data)
            };
            var t_type = data.strength ? (data.strength.toUpperCase() || "TS") : "TS";
            // var fPathData = data.forcastDataList; // forcast_PGTW_DateList forcast_RJTD_DateList
            var fPathData = {
                'BABJ': data.forcastDataList || [],
                'RJTD': data.forcast_RJTD_DateList || [],
                'PGTW': data.forcast_PGTW_DateList || []
            };
            //绘制台风中心点
            this.drawTyphoonCircleMarker(tfbh, L.latLng(lat, lng));
            //绘制台风风圈
            this.drawTyphoonWindCircle(tfbh, wcData);

            //绘制台风路径点
            this.drawTyphoonPathPoint_(tfbh, [lat, lng], t_type, wcData, fPathData, false, that.parseTyphoonLabel(tfbh, name, data), "BABJ");
            if (idx != 0) {
                //绘制台风路径
                var cur_latlng = [lat, lng];
                var pre_latlng = [dataArr[idx - 1].lat, dataArr[idx - 1].lon];

                this.drawTyphoonPath(tfbh, [pre_latlng, cur_latlng], t_type, false, "BABJ");
            }

            this.t_layers[tfbh].t_f_babj_path_layers.clearLayers();
            this.t_layers[tfbh].t_f_babj_path_point_layers.clearLayers();
            this.t_layers[tfbh].t_f_rjtd_path_layers.clearLayers();
            this.t_layers[tfbh].t_f_rjtd_path_point_layers.clearLayers();
            this.t_layers[tfbh].t_f_pgtw_path_layers.clearLayers();
            this.t_layers[tfbh].t_f_pgtw_path_point_layers.clearLayers();

            $.each(fPathData, function (key) {
                var _forcastData = $(this);
                // console.info(_forcastData);
                if (_forcastData != null) {
                    var lenPath = _forcastData.length;
                    for (var i = 0; i < lenPath; i++) {
                        var subFPathData = _forcastData[i];

                        var flat = subFPathData.lat;
                        var flng = subFPathData.lon;
                        var fType = subFPathData.strength ? subFPathData.strength.toUpperCase() || "TS" : "TS";

                        //绘制台风预报路径点
                        that.drawTyphoonPathPoint_(tfbh, [flat, flng], fType, null, null, true, that.parseTyphoonForecastLabel(tfbh, name, subFPathData, key), key);
                        //绘制台风预报路径
                        var f_cur_latlng = [flat, flng];
                        var f_pre_latlng;
                        if (i == 0) {
                            f_pre_latlng = [lat, lng];
                        } else {
                            f_pre_latlng = [_forcastData[i - 1].lat, _forcastData[i - 1].lon];
                        }
                        that.drawTyphoonPath(tfbh, [f_pre_latlng, f_cur_latlng], fType, true, key);
                    }
                }
            });
        }
    },
    drawTyphoon: function (typhoonData) {
        var tfbh = typhoonData[3];
        var name = typhoonData[2];
        var dataArr = typhoonData[8];

        //初始化台风图层对象
        this.resetTyphoonLayers(tfbh);
        var pathLen = dataArr.length;
        for (var idx = 0; idx < pathLen; idx++) {
            var data = dataArr[idx];
            var lng = data[4];
            var lat = data[5];
            var wcData = {
                'lat': lat,
                'lng': lng,
                'wc': data[10]
            };
            var t_type = data[3].toUpperCase();
            var fPathData = null;
            if (data[11] != null) {
                fPathData = data[11]['BABJ']
            }


            //绘制台风中心点
            this.drawTyphoonCircleMarker(tfbh, L.latLng(lat, lng))
            //绘制台风风圈
            this.drawTyphoonWindCircle(tfbh, wcData);

            // var _attr_ = {'tfbh': tfbh, 'wc': wcData, 'f_path_data': fPathData}
            //绘制台风路径点
            this.drawTyphoonPathPoint(tfbh, [lat, lng], t_type, wcData, fPathData, false, "<div>" + tfbh + ":" + name + "</div>");

            if (idx != 0) {
                //绘制台风路径
                var cur_latlng = [lat, lng];
                var pre_latlng = [dataArr[idx - 1][5], dataArr[idx - 1][4]];

                this.drawTyphoonPath(tfbh, [pre_latlng, cur_latlng], t_type, false);
            }


            this.t_layers[tfbh].t_f_path_layers.clearLayers();
            this.t_layers[tfbh].t_f_path_point_layers.clearLayers();
            if (fPathData != null) {


                var lenPath = fPathData.length;
                for (var i = 0; i < lenPath; i++) {
                    var subFPathData = fPathData[i];

                    var flat = subFPathData[2];
                    var flng = subFPathData[3];
                    var fType = subFPathData[7].toUpperCase();

                    //绘制台风预报路径点
                    this.drawTyphoonPathPoint(tfbh, [flat, flng], fType, null, null, true, "<div>" + tfbh + ":" + name + "</div>")
                    //绘制台风预报路径
                    var f_cur_latlng = [flat, flng];
                    var f_pre_latlng;
                    if (i == 0) {
                        f_pre_latlng = [lat, lng];
                    } else {
                        f_pre_latlng = [fPathData[i - 1][3], fPathData[i - 1][2]];
                    }
                    this.drawTyphoonPath(tfbh, [f_pre_latlng, f_cur_latlng], fType, true);

                }
            }
        }
    },
    selectedTyphoonPoint: function () {

    },
    resetTyphoonLayers: function (tfbh) {
        if (tfbh == null || tfbh == undefined) {
            if (this.t_layers != undefined) {
                var that = this;
                var allLayers = this.t_layers;
                $.each(allLayers, function () {
                    that.map.removeLayer(this.t_layer_group);
                });
                delete that.t_layers;
            }
            return;
        }
        if (this.t_layers != undefined && this.t_layers[tfbh] && this.t_layers[tfbh].t_layer_group) {
            this.map.removeLayer(this.t_layers[tfbh].t_layer_group);
            delete this.t_layers[tfbh];
        }

        if (this.t_layers == undefined) {
            this.t_layers = {};
        }
        // "t_path_layer":{},"t_center_marker_layer":{},"t_path_point_layer":{},"t_f_path_layer":{},"t_f_path_point_layer":{}
        this.t_layers[tfbh] = {};
        this.t_layers[tfbh].t_layer_group = L.layerGroup();
        this.t_layers[tfbh].t_layer_group.addTo(this.map);


        /* path point layer group*/
        this.t_layers[tfbh].t_path_point_layers = L.layerGroup();
        this.t_layers[tfbh].t_path_point_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* path layer group*/
        this.t_layers[tfbh].t_path_layers = L.layerGroup();
        this.t_layers[tfbh].t_path_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* BABJ forecast path point layer group*/
        this.t_layers[tfbh].t_f_babj_path_point_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_babj_path_point_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* BABJ forecast path layer group*/
        this.t_layers[tfbh].t_f_babj_path_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_babj_path_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* RJTD forecast path point layer group*/
        this.t_layers[tfbh].t_f_rjtd_path_point_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_rjtd_path_point_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* RJTD forecast path layer group*/
        this.t_layers[tfbh].t_f_rjtd_path_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_rjtd_path_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* PGTW forecast path point layer group*/
        this.t_layers[tfbh].t_f_pgtw_path_point_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_pgtw_path_point_layers.addTo(this.t_layers[tfbh].t_layer_group);
        /* PGTW forecast path layer group*/
        this.t_layers[tfbh].t_f_pgtw_path_layers = L.layerGroup();
        this.t_layers[tfbh].t_f_pgtw_path_layers.addTo(this.t_layers[tfbh].t_layer_group);


    },

    getValue:function(value,name){
        var temp = "";
        if(name == "movespeed"){
            if($.trim(value)!=""&&$.trim(value)!=null&&$.trim(value)!="null"){
                temp =  value + "公里/小时";
            }
        }else if(name == "movedir"){
            if(value!=null&&value!="ALMOST"&&value.length>0 ){
                var sp = [];
                sp = value.split("");
                for(var i=0;i<sp.length;i++){
                    temp += typhoonConstants.typhoon_direction[sp[i]];
                }
            }
        }else{
            if($.trim(value)!=""&&$.trim(value)!=null&&$.trim(value)!="null"){
                temp = value;
            }
        }
        return temp;
    },

    parseTyphoonLabel: function (tfbh, name, data) {
        var arr1 = data.datetime.split(" ")[0].split("-");
        var arr2 = data.datetime.split(" ")[1].split(":");
        var dateStr = parseInt(arr1[1])+"月"+parseInt(arr1[2])+"日"+arr2[0]+"时";
        //var dateValue = new Date(data.datetime);
        //var dateStr = dateValue.getMonth() + 1 + '月' + dateValue.getDate() + '日' + (dateValue.getHours() < 10 ? ('0' + dateValue.getHours()) : dateValue.getHours()) + '时';
        // return '<div class="typhoon_routeinfo"> <div class="typhoon_routename">'+tfbh+'&nbsp&nbsp'+name+data.engname+'</div> <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td>过去时间：</td> <td>'+dateStr+'</td> </tr> <tr> <td>中心位置：</td> <td>'+data.lat+'N/'+data.lon+'E</td> </tr> <tr> <td>最大风速：</td> <td>'+data.windv+'米/秒</td> </tr> <tr> <td>中心气压：</td> <td>'+data.pressure+'百帕</td> </tr> <tr> <td>移动方向：</td> <td>'+data.movedir+'</td> </tr> <tr> <td>移动速度：</td> <td>'+data.movespeed+'公里/小时</td> </tr> </tbody> </table> </div>';
        var eleStr = '<div class="typhoon_routeinfo"> <div class="typhoon_routename">' + tfbh + '&nbsp&nbsp' + (name==data.engname?'':name) + data.engname + '</div> <table cellpadding="0" cellspacing="0" class="ty_basic_info"> <tbody> <tr> <td>过去时间：</td> <td>' + dateStr + '</td> </tr> <tr> <td>中心位置：</td> <td>' + data.lat + 'N/' + data.lon + 'E</td> </tr> <tr> <td>最大风速：</td> <td>' + data.windv + '米/秒</td> </tr> <tr> <td>中心气压：</td> <td>' + data.pressure + '百帕</td> </tr> <tr> <td>移动方向：</td> <td>' + this.getValue(data.movedir,"movedir") + '</td> </tr> <tr> <td>移动速度：</td> <td>' + this.getValue(data.movespeed,"movespeed") + '</td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="5px" class="ty_wind_info"> <tbody> <tr><td>风圈半径</td><td>东北</td><td>东南</td><td>西南</td><td>西北</td><td></td></tr> <tr><td>七级</td><td>' + this.getValue(data.wind7v1) + '</td><td>' + this.getValue(data.wind7v2) + '</td><td>' + this.getValue(data.wind7v3) + '</td><td>' + this.getValue(data.wind7v4) + '</td><td>(Km)</td></tr> <tr><td>十级</td><td>' + this.getValue(data.wind10v1) + '</td><td>' + this.getValue(data.wind10v2) + '</td><td>'
            + this.getValue(data.wind10v3) + '</td><td>' + this.getValue(data.wind10v4) + '</td><td>(Km)</td></tr> <tr><td>十二级</td><td>' + this.getValue(data.wind12v1) + '</td><td>' + this.getValue(data.wind12v2) + '</td><td>' + this.getValue(data.wind12v3) + '</td><td>' + this.getValue(data.wind12v4) + '</td><td>(Km)</td></tr> </tbody> </table> </div>';
        return eleStr;
    },
    parseTyphoonForecastLabel: function (tfbh, name, data, key) {
        var arr1 = data.datetime.split(" ")[0].split("-");
        var arr2 = data.datetime.split(" ")[1].split(":");
        var dateStr = parseInt(arr1[1])+"月"+parseInt(arr1[2])+"日"+arr2[0]+"时";
        //var dateValue = new Date(data.datetime);
        //var dateStr = dateValue.getMonth() + 1 + '月' + dateValue.getDate() + '日' + (dateValue.getHours() < 10 ? ('0' + dateValue.getHours()) : dateValue.getHours()) + '时';
        var eleStr = '<div class="typhoon_routeinfo"> <div class="typhoon_routename">' + key + ' ' + tfbh + '&nbsp&nbsp' + (name==data.engname?'':name) + data.engname + '</div> <table cellpadding="0" cellspacing="0" class="ty_basic_info"> <tbody> <tr> <td>到达时间：</td> <td>' + dateStr + '</td> </tr> <tr> <td>中心位置：</td> <td>' + data.lat + 'N/' + data.lon + 'E</td> </tr> <tr> <td>最大风速：</td> <td>' + data.windv + '米/秒</td> </tr> <tr> <td>中心气压：</td> <td>' + data.pressure + '百帕</td> </tr> </tbody> </table> </div>';
        return eleStr;
    },
    /**
     * 绘制台风 中心点
     */
    drawTyphoonCircleMarker: function (tfbh, latlng) {
        if (this.t_layers[tfbh] && this.t_layers[tfbh].t_center_marker_layer) {
            this.map.removeLayer(this.t_layers[tfbh].t_center_marker_layer);
            delete this.t_layers[tfbh].t_center_marker_layer;
        }

        this.t_layers[tfbh].t_center_marker_layer = L.bgmarker(latlng, {
            icon: L.icon({
                iconUrl: '/statics/images/tf1.gif',
                iconSize: [28, 28]
            })
        }).addTo(this.t_layers[tfbh].t_layer_group);
    },
    getWindCircleData: function (data) {
        var arr = [
            ['', data.wind7v1 || 0, data.wind7v2 || 0, data.wind7v3 || 0, data.wind7v4 || 0, null],
            ['', data.wind10v1 || 0, data.wind10v2 || 0, data.wind10v3 || 0, data.wind10v4 || 0, null],
            ['', data.wind12v1 || 0, data.wind12v2 || 0, data.wind12v3 || 0, data.wind12v4 || 0, null]
        ];
        return arr;

    },
    /**
     * 绘制台风 风圈
     * layerGroup
     */
    drawTyphoonWindCircle: function (tfbh, data) {
        /* test data */
        // var data =data|| {
        //     lat: 140.1,
        //     lng: 7.7,
        //     wc: [['30KTS', 220, 180, 180, 220, 2317686],
        //         ['50KTS', 120, 120, 120, 120, 2317686],
        //         ['64KTS', 50, 50, 60, 60, 2317686]]
        // };
        /* test data end */

        if (this.t_layers[tfbh] && this.t_layers[tfbh].t_wc_layer) {
            this.map.removeLayer(this.t_layers[tfbh].t_wc_layer);
            delete this.t_layers[tfbh].t_wc_layer;
        }

        this.t_layers[tfbh].t_wc_layer = L.layerGroup();
        this.t_layers[tfbh].t_wc_layer.addTo(this.t_layers[tfbh].t_layer_group);
        var wcLatlng = L.latLng(data.lat, data.lng);
        var wcLayer_12 = L.typhoon(wcLatlng, data.wc[2], typhoonConstants.typhoonCircle_colors[2]).addTo(this.t_layers[tfbh].t_wc_layer).bringToBack();
        var wcLayer_10 = L.typhoon(wcLatlng, data.wc[1], typhoonConstants.typhoonCircle_colors[1]).addTo(this.t_layers[tfbh].t_wc_layer).bringToBack();
        var wcLayer_7 = L.typhoon(wcLatlng, data.wc[0], typhoonConstants.typhoonCircle_colors[0]).addTo(this.t_layers[tfbh].t_wc_layer).bringToBack();

    },
    /**
     * 绘制台风 路径
     */
    drawTyphoonPath: function (tfbh, latlngs, typhoonType, isForecast, fCenter) {
        /**
         * 1、由于每一段台风路径都有相对的风级需要不同的渲染方式所以每段台风路径使用一个图层
         * 2、由于台风路径需要逐段绘制，所以将台风路径存放的layerGroup的操作（非空判断、创建、删除等）
         *    放在上一层程序
         */

        var f_layer_name = "t_f_" + fCenter.toLowerCase() + "_path_layers";

        var _layers = isForecast ? this.t_layers[tfbh][f_layer_name] : this.t_layers[tfbh].t_path_layers;

        /*test data*/
        // latlngs = latlngs || [[7.7, 140.1], [8.1, 139.5]];
        // typhoonType = typhoonType || 'TS';
        /*test data end*/

        var options = {
            color: typhoonConstants.typhone_type[fCenter][typhoonType],
            weight: 2,
            opacity: 1
        };
        if (isForecast) {
            options.dashArray = '5 5';
        }
        var polyline = L.polyline(latlngs, options).addTo(_layers);
    },


    drawTyphoonPathPoint_: function (tfbh, latlng, typhoonType, wcData, fPathData, isForecast, labelElement, fCenter) {
        var that = this;
        var f_layer_name = "t_f_" + fCenter.toLowerCase() + "_path_point_layers";
        var _layers = isForecast ? this.t_layers[tfbh][f_layer_name] : this.t_layers[tfbh].t_path_point_layers;
        var options = {
            color: typhoonConstants.typhone_type[fCenter][typhoonType],
            weight: 1,
            opacity: 1,
            fill: true,
            fillColor: typhoonConstants.typhone_type[fCenter][typhoonType],
            fillOpacity: 1
        };
        options.radius = isForecast ? 3 : 4;
        var m = L.circleMarker(latlng, options);
        m.bindLabel(labelElement, {noHide: false, className: "leaflet-label-tf"});

        m.__f_data__ = {'tfbh': tfbh, 'wc': wcData, 'f_path_data': fPathData};

        if (!isForecast) {
            m.on('click', function () {
                // alert(this.__f_data__);
                var f_data = this.__f_data__;
                //TODO 重新绘制风圈
                that.drawTyphoonWindCircle(f_data.tfbh, f_data.wc);
                //TODO 重新绘制预报路径
                //TODO 重新绘制预报路径点
                var f_path_data = f_data.f_path_data;
                that.t_layers[f_data.tfbh].t_f_babj_path_point_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_babj_path_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_rjtd_path_point_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_rjtd_path_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_pgtw_path_point_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_pgtw_path_layers.clearLayers();
                $.each(f_path_data, function (key) {
                    var _f_path_data_ = $(this);
                    if (_f_path_data_ != null) {
                        var lenPath = _f_path_data_.length;
                        for (var i = 0; i < lenPath; i++) {
                            var subFPathData = _f_path_data_[i];

                            var flat = subFPathData.lat;
                            var flng = subFPathData.lon;
                            var fType = subFPathData.strength.toUpperCase() || "TS";

                            //绘制台风预报路径点
                            that.drawTyphoonPathPoint_(f_data.tfbh, [flat, flng], fType, null, null, true, that.parseTyphoonForecastLabel(tfbh, subFPathData.chnname, subFPathData, key), key);
                            //绘制台风预报路径
                            var f_cur_latlng = [flat, flng];
                            var f_pre_latlng;
                            if (i == 0) {
                                f_pre_latlng = [f_data.wc.lat, f_data.wc.lng];
                            } else {
                                f_pre_latlng = [_f_path_data_[i - 1].lat, _f_path_data_[i - 1].lon];
                            }
                            that.drawTyphoonPath(f_data.tfbh, [f_pre_latlng, f_cur_latlng], fType, true, key);
                        }
                    }
                });
            });
        }
        m.addTo(_layers);
    },

    /**
     * 绘制台风 路径点
     */
    drawTyphoonPathPoint: function (tfbh, latlng, typhoonType, wcData, fPathData, isForecast, labelElement) {
        var that = this;
        var _layers = isForecast ? this.t_layers[tfbh].t_f_path_point_layers : this.t_layers[tfbh].t_path_point_layers;

        /*test data*/
        // latlng = latlng || [7.7, 140.1];
        // typhoonType = typhoonType || 'TS';
        /*test data end*/

        var options = {
            color: typhoonConstants.typhone_type[typhoonType],
            weight: 1,
            opacity: 1,
            fill: true,
            fillColor: typhoonConstants.typhone_type[typhoonType],
            fillOpacity: 1
        };
        options.radius = isForecast ? 3 : 4;
        var m = L.circleMarker(latlng, options);
        m.bindLabel(labelElement, {noHide: false, className: "leaflet-label-tf"});

        m.__f_data__ = {'tfbh': tfbh, 'wc': wcData, 'f_path_data': fPathData};

        if (!isForecast) {
            m.on('click', function () {
                // alert(this.__f_data__);
                var f_data = this.__f_data__;
                //TODO 重新绘制风圈
                that.drawTyphoonWindCircle(f_data.tfbh, f_data.wc);
                //TODO 重新绘制预报路径
                //TODO 重新绘制预报路径点
                var f_path_data = f_data.f_path_data;
                var lenPath = f_path_data.length;
                that.t_layers[f_data.tfbh].t_f_path_layers.clearLayers();
                that.t_layers[f_data.tfbh].t_f_path_point_layers.clearLayers();
                for (var i = 0; i < lenPath; i++) {
                    var subFPathData = f_path_data[i];

                    var flat = subFPathData[2];
                    var flng = subFPathData[3];
                    var fType = subFPathData[7].toUpperCase();

                    //绘制台风预报路径点
                    that.drawTyphoonPathPoint(f_data.tfbh, [flat, flng], fType, null, null, true, "<div>" + tfbh + ":" + name + "</div>")
                    //绘制台风预报路径
                    var f_cur_latlng = [flat, flng];
                    var f_pre_latlng;
                    if (i == 0) {
                        f_pre_latlng = [f_data.wc.lng, f_data.wc.lat];
                    } else {
                        f_pre_latlng = [f_path_data[i - 1][3], f_path_data[i - 1][2]];
                    }
                    that.drawTyphoonPath(f_data.tfbh, [f_pre_latlng, f_cur_latlng], fType, true);
                }
            });
        }
        m.addTo(_layers);
    },
    addClickLatlng: function (e) {
        //当前点
        var clickLocation = [e.latlng.lat, e.latlng.lng];
        poly_points.push(clickLocation);
        //显示折线
        poly_line.addLatLng(e.latlng);
        map.addLayer(poly_line);
        //var point=new L.Point(e.layerPoint.x,e.layerPoint.y);
    },

    measure: function () {
        var map = this.map;
        var layer = L.layerGroup();
        layer.addTo(this.map);
        var measurePoints = [];
        var totalDistance = 0;
        var start = false;
        var lines;
        var tempLine;
        var markers = [];
        var cc = function (e) {
            map.doubleClickZoom.disable();
            start = true;
            if (measurePoints.length > 0) {
                if (e.latlng.lat != measurePoints[measurePoints.length - 1].lat && e.latlng.lng != measurePoints[measurePoints.length - 1].lng) {
                    measurePoints.push(e.latlng);
                    if (measurePoints.length == 2) {
                        lines = new L.Polyline(measurePoints, {"color": "yellow", "weight": 1});
                        lines.addTo(layer);
                    }
                    var s = L.circleMarker(e.latlng, {color: "red"});
                    s.setRadius(1);
                    if (measurePoints.length >= 2) {
                        var d = measurePoints[measurePoints.length - 1].distanceTo(measurePoints[measurePoints.length - 2]);
                        totalDistance += d;
                        var txt = (d / 1000).toFixed(3) + "（公里）";//, className: "leaflet-label-tffq"
//						s.bindLabel(txt, {noHide: true, direction: 'right', clickable: true});
                        s.bindLabel(txt, {
                            noHide: true,
                            direction: 'right',
                            clickable: true,
                            className: "leaflet-label-tffq"
                        });
                    }
                    s.addTo(layer);
                    markers.push(s);
                    lines.setLatLngs(measurePoints);
                }
            } else {
                measurePoints.push(e.latlng);
                var s = L.circleMarker(e.latlng, {color: "red"});
                s.setRadius(1);
//				s.bindLabel("起点", {noHide: true, direction: 'right'});
                s.bindLabel("起点", {noHide: true, direction: 'right', className: "leaflet-label-tffq"});
                s.addTo(layer);
                markers.push(s);
            }

        };
        var mm = function (e) {
            if (start) {
                if (tempLine != null) {
                    layer.removeLayer(tempLine);
                }
                tempLine = new L.Polyline([measurePoints[measurePoints.length - 1], e.latlng], {
                    "color": "yellow",
                    "weight": 1
                });
                tempLine.addTo(layer);
            }
        };
        var dc = function (e) {
            if (measurePoints.length > 1) {
                if (markers.length > 1) {
                    var m = markers[markers.length - 1];
                    var lab = m.getLabel();
                    var tt = document.createTextNode(m.getLabel()._content + "  总长度：" + (totalDistance / 1000).toFixed(3) + "（公里）");
                    lab._container.innerHTML = "";
                    lab._container.appendChild(tt);
                    var span = document.createElement("span");
                    span.innerHTML = "【关闭】";
                    span.style.color = "#00ff40";
                    lab._container.appendChild(span);
                    L.DomEvent.addListener(span, "click", function () {
                        map.removeLayer(layer);
                    });
                }
                start = false;
                map.off("click", cc).off("mousemove", mm).off("dblclick", dc);
                $(".tool_measure").removeAttr("id");
            }
        };
        var mu = function (e) {
            map.doubleClickZoom.enable();
        };
        map.on("click", cc).on("mousemove", mm).on("dblclick", dc).on("mouseup", mu);
        this.cancelMeasure = function () {
            map.off("click", cc).off("mousemove", mm).off("dblclick", dc).off("mouseup", mu);
        };
    },
    cancelMeasure: function () {
    },

    zoomIn: function () {
        var z = this.map.getZoom();
        this.map.setZoom(++z);
    },
    zoomOut: function () {
        var z = this.map.getZoom();
        this.map.setZoom(--z);
    },
    lineStringsIntersect: function (l1, l2) {
        var intersects = [];
        for (var i = 0; i <= l1.coordinates.length - 2; ++i) {
            for (var j = 0; j <= l2.coordinates.length - 2; ++j) {
                var a1Latlon = L.latLng(l1.coordinates[i][1], l1.coordinates[i][0]),
                    a2Latlon = L.latLng(l1.coordinates[i + 1][1], l1.coordinates[i + 1][0]),
                    b1Latlon = L.latLng(l2.coordinates[j][1], l2.coordinates[j][0]),
                    b2Latlon = L.latLng(l2.coordinates[j + 1][1], l2.coordinates[j + 1][0]),
                    a1 = L.Projection.SphericalMercator.project(a1Latlon),
                    a2 = L.Projection.SphericalMercator.project(a2Latlon),
                    b1 = L.Projection.SphericalMercator.project(b1Latlon),
                    b2 = L.Projection.SphericalMercator.project(b2Latlon),
                    ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
                    ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
                    u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
                if (u_b != 0) {
                    var ua = ua_t / u_b,
                        ub = ub_t / u_b;
                    if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
                        var pt_x = a1.x + ua * (a2.x - a1.x),
                            pt_y = a1.y + ua * (a2.y - a1.y),
                            pt_xy = {
                                "x": pt_x,
                                "y": pt_y
                            },
                            pt_latlon = L.Projection.SphericalMercator.unproject(pt_xy);
                        intersects.push({
                            'type': 'Point',
                            'coordinates': [pt_latlon.lng, pt_latlon.lat]
                        });
                    }
                }
            }
        }
        if (intersects.length == 0) intersects = false;
        return intersects;
    },
    lineify: function (inputGeom) {
        var outputLines = {
            "type": "GeometryCollection",
            "geometries": []
        }
        switch (inputGeom.type) {
            case "GeometryCollection":
                for (var i in inputGeom.geometries) {
                    var geomLines = this.lineify(inputGeom.geometries[i]);
                    if (geomLines) {
                        for (var j in geomLines.geometries) {
                            outputLines.geometries.push(geomLines.geometries[j]);
                        }
                    } else {
                        outputLines = false;
                    }
                }
                break;
            case "Feature":
                var geomLines = this.lineify(inputGeom.geometry);
                if (geomLines) {
                    for (var j in geomLines.geometries) {
                        outputLines.geometries.push(geomLines.geometries[j]);
                    }
                } else {
                    outputLines = false;
                }
                break;
            case "FeatureCollection":
                for (var i in inputGeom.features) {
                    var geomLines = this.lineify(inputGeom.features[i].geometry);
                    if (geomLines) {
                        for (var j in geomLines.geometries) {
                            outputLines.geometries.push(geomLines.geometries[j]);
                        }
                    } else {
                        outputLines = false;
                    }
                }
                break;
            case "LineString":
                outputLines.geometries.push(inputGeom);
                break;
            case "MultiLineString":
            case "Polygon":
                for (var i in inputGeom.coordinates) {
                    outputLines.geometries.push({
                        "type": "LineString",
                        "coordinates": inputGeom.coordinates[i]
                    });
                }
                break;
            case "MultiPolygon":
                for (var i in inputGeom.coordinates) {
                    for (var j in inputGeom.coordinates[i]) {
                        outputLines.geometries.push({
                            "type": "LineString",
                            "coordinates": inputGeom.coordinates[i][j]
                        });
                    }
                }
                break;
            default:
                outputLines = false;
        }
        return outputLines;
    },
    crossCheck: function (baseLayer, drawLayer) {
        var baseJson = baseLayer.toGeoJSON(),
            drawJson = drawLayer.toGeoJSON(),
            baseLines = this.lineify(baseJson),
            drawLines = this.lineify(drawJson),
            crossPoints = {
                type: "GeometryCollection",
                geometries: []
            };
        if (baseLines && drawLines) {
            for (var i in drawLines.geometries) {
                for (var j in baseLines.geometries) {
                    var crossTest = this.lineStringsIntersect(drawLines.geometries[i], baseLines.geometries[j]);
                    if (crossTest) {
                        for (var k in crossTest) {
                            crossPoints.geometries.push(crossTest[k]);
                        }
                    }
                }
            }
        }
        return crossPoints;
    },

    /**
     * typhoonMap.toogleForcastLayers('BABJ',true);//显示
     * typhoonMap.toogleForcastLayers('BABJ',false);//隐藏
     * @param fCenter
     * @param flag
     */
    toogleForcastLayers: function (fCenter,flag) {
        var all_t_layers = this.t_layers;
        var fcenter = fCenter.toLowerCase();
        var f_path_layer_name = "t_f_" + fcenter + "_path_layers";
        var f_path_point_layer_name = "t_f_" + fcenter + "_path_point_layers";
        $.each(all_t_layers, function (tfbh) {
            var _t_layers = all_t_layers[tfbh];
            if(flag){
                _t_layers[f_path_layer_name].addTo(_t_layers.t_layer_group);
                _t_layers[f_path_point_layer_name].addTo(_t_layers.t_layer_group);
            }else {
                _t_layers.t_layer_group.removeLayer(_t_layers[f_path_layer_name]);
                _t_layers.t_layer_group.removeLayer(_t_layers[f_path_point_layer_name]);
            }
        });
    }
};

